#删除xml中某一类
import os
import xml.etree.ElementTree as ET
yuan_dir = '/home/xys/datasets/dataset_che/Vehicle/xml/'  # 设置原始标签路径为 Annos
new_dir = '/home/xys/datasets/dataset_che/Vehicle/shanhou/'  # 设置新标签路径 Annotations
class_path = '/home/xys/datasets/dataset_che/Vehicle/新建文本.txt'
def get_class(path):
    with open(path) as f:
        class_names = f.readlines()
    class_names = [c.strip() for c in class_names]
    return class_names

class_names = get_class(class_path)
for filename in os.listdir(yuan_dir):
    file_path = os.path.join(yuan_dir, filename)
    new_path=os.path.join(new_dir,filename)
    dom = ET.parse(file_path)
    root = dom.getroot()
    del_list = []
    for obj in root.iter('object'):  # 获取object节点中的name子节点
        if obj.find('name').text in class_names:
            del_list.append(obj)
    for i in del_list:
        root.remove(i)
    dom.write(new_path, xml_declaration=True)